package com.tsd.core.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @ClassName: ThreadPoolTaskConfig
 * @Description: 线程池配置
 * @Author: Hillpool
 * @Date: 2022/7/28 15:06
 * @Version: 1.0
 */
@Configuration
public class ThreadPoolTaskConfig {

    private static final int CORE_POOL_SIZE = 10;
    private static final int MAX_POOL_SIZE = 1000;
    private static final int KEEP_ALIVE_SECONDS = 300;
    private static final int QUEUE_CAPACITY = 200;

    // 主线程池
    @Bean("threadPoolTaskExecutor")
    @Primary
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 线程池维护线程的最少数量
        executor.setCorePoolSize(20);
        // 线程池维护线程的最大数量
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        // 线程池所使用的缓冲队列
        executor.setQueueCapacity(QUEUE_CAPACITY);
        // 线程池维护线程所允许的空闲时间
        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        // 执行初始化
        executor.initialize();
        return executor;
    }

    @Bean(name = "serviceJobTaskExecutor")
    public ThreadPoolTaskExecutor serviceJobTaskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //线程池维护线程的最少数量
        taskExecutor.setCorePoolSize(CORE_POOL_SIZE);
        //线程池维护线程的最大数量
        taskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
        //线程池所使用的缓冲队列
        taskExecutor.setQueueCapacity(QUEUE_CAPACITY);
        //线程池维护线程所允许的空闲时间
        taskExecutor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        // 等待所有任务结束后再关闭线程池
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        // 执行初始化
        taskExecutor.initialize();
        return taskExecutor;
    }
}
